# -*- coding: utf-8 -*-

import datetime
import decimal

from werkzeug.contrib.cache import RedisCache
from flask_mongoengine import MongoEngine
from mongoengine import signals, Document
from bson import ObjectId

from app.utils.time_utils import isoformat


class BaseDocument(Document):
    meta = {'abstract': True}

    def as_dict(self, exclude=set(), only=set()):
        """ 把一个 Model 对象转换成 dict
        :param exclude: 排除的 fields
        :param only: 只保留的 fields，如果指定了 only，将忽略 exclude
        :return: dict
        """
        rv = {}
        fields = set(self._fields.keys())
        if only:
            fields &= set(only)
        elif exclude:
            fields -= set(exclude)
        for field in fields:
            value = getattr(self, field)
            if isinstance(value, (datetime.datetime, datetime.date)):
                value = isoformat(value)
            elif isinstance(value, ObjectId):
                value = str(value)
            elif isinstance(value, decimal.Decimal):
                value = value and str(value) or '0.0'
            # elif isinstance(value, dict) and '$oid' in value:
            #     print value
                # value = value.get('$oid')
            #     field = 'id'
            #     print field

            rv[field] = value
        return rv

    @classmethod
    def find_one(cls, **queryset):
        return cls.objects.filter(**queryset).first()

    @classmethod
    def find_or_create(cls, **kwargs):
        row = cls.find_one(**kwargs)
        if not row:
            row = cls()
            for k, v in kwargs.iteritems():
                setattr(row, k, v)
        return row
